package top.fengleifeng.question;

/**
 * @author : fengleifeng
 * @Package top.fengleifeng.question
 * @Description:
 * @date Date : 2020年11月25日 3:44 下午
 */
public class Y剑指67把字符串转换成整数 {

    class Solution {

        public int strToInt(String str) {
            if (str == null || str.trim() == "") {
                return 0;
            }
            str = str.trim();
            char[] chars = str.toCharArray();
            boolean flag = true;
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < chars.length; i++) {
                if (flag) {
                    if (chars[i] == '-' || chars[i] == '+') {
                        sb.append(chars[i]);

                    } else if (chars[i] >= '0' && chars[i] <= '9') {
                        sb.append(chars[i]);
                    } else {
                        return 0;
                    }
                    flag = false;
                    continue;
                }
                if (chars[i] >= '0' && chars[i] <= '9') {
                    sb.append(chars[i]);
                } else {

                    break;
                }
            }
            //判断
            String result = sb.toString();
            if (result.length() == 1 && (result.equals("+") || result.equals("-"))) {
                return 0;
            }
            if (result.length() > 11) {
                if (result.charAt(0) == '-') {
                    return Integer.MIN_VALUE;
                } else {
                    return Integer.MAX_VALUE;
                }
            } else if (result.length() == 11) {
                if (result.charAt(0) == 45) {
                    String s = str.substring(0, str.length() - 1);
                    int temp = Integer.parseInt(str.substring(str.length() - 1, str.length()));
                    if (Integer.parseInt(s) <= -214748364 && temp > -(Integer.MIN_VALUE % 10)) {
                        return Integer.MIN_VALUE;
                    }
                } else if (result.charAt(0) == 43) {
                    String s = str.substring(0, str.length() - 1);
                    int temp = Integer.parseInt(str.substring(str.length() - 1, str.length()));
                    if (Integer.parseInt(s) >= 214748364 && temp > (Integer.MAX_VALUE % 10)) {
                        return Integer.MAX_VALUE;
                    }
                } else {
                    return Integer.MAX_VALUE;
                }
            } else {
                return Integer.parseInt(result);
            }
            return 0;
        }
    }

    public static void main(String[] args) {
        String str = "";
        int i = new Y剑指67把字符串转换成整数().new Solution().strToInt(str);
        System.out.println(i);
    }
}
